import { DeepPartial, FindManyOptions, UpdateResult } from "typeorm";
import { Post } from "../entities";
import { AppDataSource } from "../data-source";

export class PostService {
  private static readonly postRepository = AppDataSource.getRepository(Post);

  public static async create(payload: DeepPartial<Post>): Promise<Post> {
    const create = this.postRepository.create(payload);
    return this.postRepository.save(create);
  }

  public static async findById(id: Post["id"]): Promise<Post | null> {
    return this.postRepository.findOne({
      where: { id },
      relations: ["attachments", "user", "board"],
    });
  }

  public static async find(
    options: FindManyOptions<Post>,
  ): Promise<[Post[], number]> {
    return this.postRepository.findAndCount({
      ...options,
      relations: ["attachments", "user", "board"],
    });
  }

  public static async update(
    id: Post["id"],
    payload: DeepPartial<Post>,
  ): Promise<UpdateResult> {
    return this.postRepository.update({ id }, payload);
  }

  public static async remove(post: Post): Promise<Post> {
    return this.postRepository.remove(post);
  }
}
